package com.yiwei.zhh.activity;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yiwei.zhh.R;
import com.yiwei.zhh.api.callback.ChsiForgetContract;
import com.yiwei.zhh.api.requestInfo.ChsiForgetPwdRequest;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.model.ChsiModel;
import com.yiwei.zhh.model.ChsiPwdModel;
import com.yiwei.zhh.util.DisplayUtil;
import com.yiwei.zhh.util.ImageUtil;
import com.yiwei.zhh.util.StatusBarCompat;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.UI;
import com.yiwei.zhh.view.CircularProgress;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

/**
 * 学信网忘记密码界面
 * Created by Master.Dong on 16/4/10.
 */
public class ChsiForgetPwdV2Activity extends BaseActivity implements ChsiForgetContract.View {


    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.img_code)
    ImageView imgCode;
    @BindView(R.id.cb_agree)
    CheckBox cbAgree;
    @BindView(R.id.txt_agree)
    TextView txtAgree;
    @BindView(R.id.progressBar)
    CircularProgress loading;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.layout_view1)
    LinearLayout layoutView1;
    @BindView(R.id.type_v_phone)
    TextView typeVPhone;
    @BindView(R.id.type_v_phone_view)
    RelativeLayout typeVPhoneView;
    @BindView(R.id.type_v_email)
    TextView typeVEmail;
    @BindView(R.id.type_v_email_view)
    RelativeLayout typeVEmailView;
    @BindView(R.id.type_view)
    LinearLayout typeView;
    @BindView(R.id.email_v_email)
    EditText emailVEmail;
    @BindView(R.id.email_v_realname)
    EditText emailVRealname;
    @BindView(R.id.email_v_idno)
    EditText emailVIdno;
    @BindView(R.id.find_by_phone)
    TextView findByPhone;
    @BindView(R.id.email_v_btn)
    TextView emailVBtn;
    @BindView(R.id.email_view)
    LinearLayout emailView;
    @BindView(R.id.phone_v_phone)
    EditText phoneVPhone;
    @BindView(R.id.phone_v_realname)
    EditText phoneVRealname;
    @BindView(R.id.phone_v_idno)
    EditText phoneVIdno;
    @BindView(R.id.phone_v_code)
    EditText phoneVCode;
    @BindView(R.id.phone_v_img_code)
    ImageView phoneVImgCode;
    @BindView(R.id.phone_v_btn)
    TextView phoneVBtn;
    @BindView(R.id.phone_view)
    LinearLayout phoneView;
    @BindView(R.id.pwd_v_tishi)
    TextView pwdVTishi;
    @BindView(R.id.pwd_v_code)
    EditText pwdVCode;
    @BindView(R.id.pwd_v_code_btn)
    TextView pwdVCodeBtn;
    @BindView(R.id.pwd_v_new_pwd)
    EditText pwdVNewPwd;
    @BindView(R.id.see)
    CheckBox see;
    @BindView(R.id.find_by_email)
    TextView findByEmail;
    @BindView(R.id.pwd_v_btn)
    TextView pwdVBtn;
    @BindView(R.id.pwd_view)
    LinearLayout pwdView;
    @BindView(R.id.result_icon)
    ImageView resultIcon;
    @BindView(R.id.result_title)
    TextView resultTitle;
    @BindView(R.id.result_text)
    TextView resultText;
    @BindView(R.id.result_view)
    LinearLayout resultView;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    private ChsiForgetPwdRequest api;
    private int viewIndex = 1;  //返回按钮判断
    private String ctoken, clst, mobile, email;
    private Unbinder unbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chsi_pwd_v2_activity);
        unbinder = ButterKnife.bind(this);
        baseInitView(this, "ChsiForgetPwdV2Activity", Const.ViewType.ACTIVITY);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏

            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(Color.TRANSPARENT);
            tintManager.setNavigationBarTintColor(Color.parseColor("#000000"));
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setNavigationBarTintEnabled(true);
        }
        initView();

    }

    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            btnBack.post(new Runnable() {
                @Override
                public void run() {
                    int height = StatusBarCompat.getStatusBarHeight(ChsiForgetPwdV2Activity.this);
                    if (height == 0) {
                        return;
                    }

                    int left = DisplayUtil.dip2px(ChsiForgetPwdV2Activity.this, 10);
                    if (btnBack != null)
                        btnBack.setPadding(left, height + left, 0, left);
                }
            });
        }
        api = ChsiForgetPwdRequest.create();
        api.attachView(this);
        api.getChsiImgCodeInfo(true, 0);


        see.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    see.setBackgroundResource(R.mipmap.see_off);
                    pwdVNewPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); //显示密码
                } else {
                    see.setBackgroundResource(R.mipmap.see);
                    pwdVNewPwd.setTransformationMethod(PasswordTransformationMethod.getInstance()); //隐藏密码
                }
                pwdVNewPwd.setSelection(pwdVNewPwd.getText().length());
            }
        });
    }

    private void jumpView() {
        if (viewIndex == 2) showView(1);
        else if (viewIndex == 3) showView(2);
        else if (viewIndex == 4) showView(2);
        else if (viewIndex == 5) showView(4);
//        else if (viewIndex == 0) {
//            resultView.setVisibility(View.GONE);
//            viewIndex = 1;
        else
            finish();
    }

    private boolean mark = false;

    @OnTextChanged({R.id.edit_code, R.id.edit_phone})
    void afterTextChanged(Editable s) {
        if (UI.toString(editCode).length() != 0 && UI.toString(editPhone).length() != 0) {
//            填完了数据
            if (!mark) {
                mark = true;
                btnSubmit.setBackgroundResource(R.drawable.btn_chsi_register_true);

            }
        } else {
//            还没填完
            if (mark) {
                mark = false;
                btnSubmit.setBackgroundResource(R.drawable.btn_chsi_register);
            }
        }
    }

    @OnTextChanged({R.id.pwd_v_code, R.id.pwd_v_new_pwd})
    void afterTextChangedPwd(Editable s) {
        if (UI.toString(pwdVCode).length() != 0 && UI.toString(pwdVNewPwd).length() != 0) {
//            填完了数据
            if (!mark) {
                mark = true;
                pwdVBtn.setBackgroundResource(R.drawable.btn_chsi_register_true);

            }
        } else {
//            还没填完
            if (mark) {
                mark = false;
                pwdVBtn.setBackgroundResource(R.drawable.btn_chsi_register);
            }
        }
    }

    @OnTextChanged({R.id.email_v_email, R.id.email_v_realname, R.id.email_v_idno})
    void afterTextChangedEmail(Editable s) {
        if (UI.toString(emailVEmail).length() != 0 && UI.toString(emailVRealname).length() != 0 && UI.toString(emailVIdno).length() != 0) {
//            填完了数据
            if (!mark) {
                mark = true;
                emailVBtn.setBackgroundResource(R.drawable.btn_chsi_register_true);

            }
        } else {
//            还没填完
            if (mark) {
                mark = false;
                emailVBtn.setBackgroundResource(R.drawable.btn_chsi_register);
            }
        }
    }


    @OnTextChanged({R.id.phone_v_phone, R.id.phone_v_realname, R.id.phone_v_idno, R.id.phone_v_code})
    void afterTextChangedPhone(Editable s) {
        if (UI.toString(phoneVPhone).length() != 0 && UI.toString(phoneVRealname).length() != 0 && UI.toString(phoneVIdno).length() != 0 && UI.toString(phoneVCode).length() != 0) {
//            填完了数据
            if (!mark) {
                mark = true;
                phoneVBtn.setBackgroundResource(R.drawable.btn_chsi_register_true);

            }
        } else {
//            还没填完
            if (mark) {
                mark = false;
                phoneVBtn.setBackgroundResource(R.drawable.btn_chsi_register);
            }
        }
    }

    private void showView(int index) {
        // codeView, typeView, emailView, phoneView, pwdView;
        viewIndex = index;
        if (TextUtils.isEmpty(mobile)) findByPhone.setVisibility(View.INVISIBLE);
        if (TextUtils.isEmpty(email)) findByEmail.setVisibility(View.INVISIBLE);

        layoutView1.setVisibility(View.GONE);
        typeView.setVisibility(View.GONE);
        emailView.setVisibility(View.GONE);
        phoneView.setVisibility(View.GONE);
        pwdView.setVisibility(View.GONE);

        if (index == 1) {
            layoutView1.setVisibility(View.VISIBLE);
        } else if (index == 2) {
            typeView.setVisibility(View.VISIBLE);
        } else if (index == 3) {
            emailView.setVisibility(View.VISIBLE);
        } else if (index == 4) {
            phoneView.setVisibility(View.VISIBLE);
        } else if (index == 5) pwdView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onBackPressed() {
        jumpView();
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {
        showLoading(false);
    }

    @Override
    public void onRequestStart() {
        showLoading(true);
    }

    @Override
    public void getChsiImgCodeInfoSuccess(int type, ChsiModel model) {
        String imgStr = "";
        String captcha = model.data.getCaptcha();
        if (captcha.contains(",")) {
            imgStr = captcha.substring(captcha.indexOf(',') + 1);
            if (type == 0)
                imgCode.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));
            if (type == 1) phoneVImgCode.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));

        } else imgCode.setImageDrawable(null);
    }

    @Override
    public void getChsiPwdTypeInfoSuccess(ChsiPwdModel model) {
        ctoken = model.getCtoken();
        mobile = model.getData().getMobile();
        email = model.getData().getEmail();
        if (model.getStatus() == 1) {
            if (!TextUtils.isEmpty(mobile)) {
                typeVPhone.setText(model.getData().getMobile());
                typeVPhoneView.setVisibility(View.VISIBLE);
                getChsiCode(1);
            }
            if (!TextUtils.isEmpty(email)) {
                typeVEmail.setText(model.getData().getEmail());
                typeVEmailView.setVisibility(View.VISIBLE);
                emailVEmail.setText(email);
            }
            showView(2);
        } else {
            editCode.setText("");
            if (model.getMsg().contains(getString(R.string.code)))
                ToastUtil.makeText(getApplicationContext(), model.getMsg(), Toast.LENGTH_SHORT).show();
            else showResultView(false, getString(R.string.find_fail), model.getMsg());
            getChsiCode(0);
        }
    }

    /**
     * 验证码计时器
     */
    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            if (pwdVCodeBtn != null) {
                pwdVCodeBtn.setEnabled(false);
                pwdVCodeBtn.setText((millisUntilFinished / 1000) + getResources().getString(R.string.resend));
                pwdVCodeBtn.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
            }
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        pwdVCodeBtn.setEnabled(true);
        pwdVCodeBtn.setText(getResources().getString(R.string.get_code));
        pwdVCodeBtn.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.blue));
    }

    private void showResultView(boolean bool, String title, String text) {
        if (bool) {
            viewIndex = 100;
            resultIcon.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.check));
        } else {
            viewIndex = 0;
            resultIcon.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.fall));
        }

        resultTitle.setText(title);
        resultText.setText(text);
        layoutView1.setVisibility(View.GONE);
        typeView.setVisibility(View.GONE);
        emailView.setVisibility(View.GONE);
        phoneView.setVisibility(View.GONE);
        pwdView.setVisibility(View.GONE);
        resultView.setVisibility(View.VISIBLE);
    }

    /**
     * 获取学信网图形验证码
     */
    private void getChsiCode(final int type) {
        editCode.setText("");
        api.getChsiImgCodeInfo(false, type);
    }

    @Override
    public void getRetrieveByEmailInfoSuccess(ChsiModel model) {
        if (model.getStatus() == 1) {
            showResultView(true, model.getMsg(), model.data.getDescription());
        } else if (model.getStatus() == 0) {
            showResultView(false, model.getMsg(),model.data.getDescription());
        }
        ToastUtil.makeText(getApplicationContext(), model.getMsg(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getRetrieveByPhoneInfoSuccess(ChsiModel model) {
        if (model.getStatus() == 1) {
            clst = model.data.getClst();
            timer.start();
            showView(5);
        } else if (model.getStatus() == 0) {
            phoneVCode.setText("");
            ToastUtil.makeText(getApplicationContext(), model.data.getDescription(), Toast.LENGTH_SHORT).show();
            getChsiCode(1);
        }
    }

    @Override
    public void getRetrieveByPhoneInfo2Success(ChsiModel model) {
        showResultView(true, model.getMsg(), model.data.getDescription());
    }


    @OnClick({R.id.ok, R.id.btn_back, R.id.btn_submit, R.id.img_code, R.id.email_v_btn, R.id.phone_v_btn, R.id.pwd_v_btn, R.id.phone_v_img_code, R.id.type_v_phone_view, R.id.type_v_email_view, R.id.find_by_phone, R.id.find_by_email, R.id.pwd_v_code_btn})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ok:
                finish();
                break;
            case R.id.btn_back:
                jumpView();
                break;
            case R.id.btn_submit:
                if (codeViewInputCheck()) {
                    try {
                        api.getChsiPwdTypeInfo(URLEncoder.encode(editPhone.getText().toString(), "UTF-8"), URLEncoder.encode(editCode.getText().toString(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.img_code:
                getChsiCode(0);
                break;
            case R.id.email_v_btn:
                if (emailViewInputCheck())
                    getPwdByEmail();
                break;
            case R.id.phone_v_btn:
                if (phoneViewInputCheck())
                    getPwdByPhone();
                break;
            case R.id.pwd_v_btn:
                if (phoneViewInputCheck2())
                    getPwdByPhone2();
                break;
            case R.id.phone_v_img_code:
                getChsiCode(1);
                break;
            case R.id.type_v_phone_view:
                showView(4);
                break;
            case R.id.type_v_email_view:
                showView(3);
                break;
            case R.id.find_by_phone:
                showView(4);
                break;
            case R.id.find_by_email:
                showView(3);
                break;
            case R.id.pwd_v_code_btn:
                phoneVCode.setText("");
                pwdVCode.setText("");
                pwdVNewPwd.setText("");
                showView(4);
                getChsiCode(1);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        api.detachView();
        api = null;
        unbinder.unbind();
        unbinder = null;
    }

    /**
     * 通过手机找回密码
     */
    private void getPwdByPhone() {
        try {
            api.getRetrieveByPhoneInfo(ctoken, phoneVPhone.getText().toString(), URLEncoder.encode(phoneVRealname.getText().toString(), "UTF-8"), phoneVIdno.getText().toString(), URLEncoder.encode(phoneVCode.getText().toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过手机找回密码
     */
    private void getPwdByPhone2() {
        api.getRetrieveByPhoneInfo2(clst, pwdVCode.getText().toString(), pwdVNewPwd.getText().toString());
    }

    /**
     * 通过email找回密码
     */
    private void getPwdByEmail() {
        try {
            api.getRetrieveByEmailInfo(ctoken, emailVEmail.getText().toString(), URLEncoder.encode(emailVRealname.getText().toString(), "UTF-8"), emailVIdno.getText().toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 手机界面非空判断
     *
     * @return
     */
    private boolean phoneViewInputCheck2() {
        if (TextUtils.isEmpty(pwdVCode.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(pwdVNewPwd.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.password_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    /**
     * 手机界面非空判断
     *
     * @return
     */
    private boolean phoneViewInputCheck() {
        if (TextUtils.isEmpty(phoneVPhone.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.phone_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(phoneVRealname.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.realname_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(phoneVIdno.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.idcard_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(phoneVCode.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 验证码界面非空判断
     *
     * @return
     */
    private boolean codeViewInputCheck() {
        if (TextUtils.isEmpty(editPhone.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.account_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(editCode.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 安全邮箱界面非空判断
     *
     * @return
     */
    private boolean emailViewInputCheck() {
        if (TextUtils.isEmpty(emailVEmail.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.email_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(emailVRealname.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.realname_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(emailVIdno.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getString(R.string.idcard_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void showLoading(boolean b) {
        if (loading != null) {
            if (b)
                loading.setVisibility(View.VISIBLE);
            else
                loading.setVisibility(View.GONE);
        }
    }

}
